package com.jiechuang.user.annotation.parse;

import com.jiechuang.common.annotation.JWTPermission;
import com.jiechuang.common.exception.NoPermissionException;
import com.jiechuang.common.util.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Aspect
@Component
@Slf4j
public class JWTPermissionParse {
    //public static final ThreadLocal<LogRecord> THREAD_LOCAL=new ThreadLocal<>();
    //日志service注入
    @Autowired
    private JWTUtil jwtUtil;
    //JWTPermission
    @Pointcut(value = "@annotation(jwtPermission)")
    public void cut(JWTPermission jwtPermission){
    }
    //进入切点前封装对象进ThreadLocal
    @Before(value = "cut(jwtPermission)")
    public void doBefore(JoinPoint joinPoint, JWTPermission jwtPermission){
        if(!"all".equals(jwtPermission)){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String authorization = request.getHeader("Authorization");
            try {
                Claims claims = jwtUtil.parseJWT(authorization);
                List<String> roleCodes = (List<String>) claims.get("roleCodes");
                if(CollectionUtils.isEmpty(roleCodes)){
                    throw new NoPermissionException("无权限");
                }
                if(!roleCodes.contains(jwtPermission.role())&&!roleCodes.contains("admin")){
                    throw new NoPermissionException("无权限");
                }
            } catch (io.jsonwebtoken.ExpiredJwtException e){
                e.printStackTrace();
                throw new RuntimeException("令牌有效期已到，请重新登录");
            }catch (NoPermissionException e) {
                e.printStackTrace();
                throw new NoPermissionException(e.getMessage());
            }catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("令牌不正确，请重新登录");
            }
        }
    }

}
